<?php
/**--------------------
 * Date: 2018/3/1
 * FileName:Goods.php 物品操作
 * ProjectName:ZhiShiRongYao
 * -------------------- */


namespace app\api\controller;


use think\Db;
use think\Exception;

class Goods extends Base
{

    /**
     * 系统物品奖励列表
     *
     * @param $type int 奖励类型（1:登陆奖励,2:系统维护3:活动，4:其他）
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function systemGoodsList($type = 0)
    {
        if (!$type) {
            return $this->json_error('暂无物品列表');
        }
        $list_box  = Db::name('system_reward')
                       ->alias('s')
                       ->field('name,logo,target_id,target_type,s.num,s.sort')
                       ->join('zp_box b', 's.target_id=b.id')
                       ->where('s.type', $type)
                       ->where('target_type', 1)
                       ->order("sort")
                       ->select();
        $list_prop = Db::name('system_reward')
                       ->alias('s')
                       ->field('name,logo,target_id,target_type,s.num,s.sort')
                       ->join('zp_prop p', 's.target_id=p.id')
                       ->where('s.type', $type)
                       ->where('target_type', 2)
                       ->order("sort")
                       ->select();
        /** @var array $list_box */
        /** @var array $list_prop */
        $lists = array_merge($list_box, $list_prop);
        array_multisort(array_column($lists, 'sort'), SORT_ASC, $lists);
        //$now_time = date('w');
        //if ($now_time == 0) {
        //    $now_time = 7;
        //}
        //   $start_time = strtotime(date('Y-m-d', strtotime('-'.($now_time - 1).'days')));
        $user_list = Db::name('reward_log r')
                       ->field('s.sort')
                       ->join('system_reward s', 'r.extra_int=s.id')
                       ->where([
                                   'user_id' => $this->user_info['id'],
                                   'stage'   => 'login'
                               ])
                       ->order('r.create_time', 'desc')
                       ->find();
        foreach ($lists as $k => &$v) {
            $v['is_get'] = 0;
            if ($user_list['sort']!=7&&$v['sort'] <= $user_list['sort']) {
                $v['is_get'] = 1;
            }
        }
        return $this->json_success('ok', $lists);
    }

    /**
     * 领取登录奖励
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSysAward()
    {
        $start_time = strtotime(date('Y-m-d'));
        //判断当天
        $log = Db::name('reward_log')
                 ->where([
                             'user_id'     => $this->user_info['id'],
                             'stage'       => 'login',
                             'create_time' => [
                                 '>',
                                 $start_time
                             ]
                         ])
                 ->find();
        if (!$log) {
            $res = Db::name('reward_log r')
                     ->field('s.sort')
                     ->join('system_reward s', 'r.extra_int=s.id')
                     ->where([
                                 'user_id' => $this->user_info['id'],
                                 'stage'   => 'login'
                             ])
                     ->order('r.create_time', 'desc')
                     ->find();

            $sort = $res['sort'];
            if ($sort == 7) {
                $sort = 1;
            } else {
                $sort += 1;
            }
            $award_detail = Db::name('system_reward')
                              ->where([
                                          'type' => 1,
                                          'sort' => $sort
                                      ])
                              ->find();
            if ($award_detail) {
                $table = Db::name('user_goods');
                $goods = $table->where([
                                           'target_type' => $award_detail['target_type'],
                                           'target_id'   => $award_detail['target_id'],
                                           'user_id'     => $this->user_info['id']
                                       ])
                               ->find();
                Db::startTrans();
                try {
                    if ($goods) {
                        $table->where('id', $goods['id'])
                              ->update([
                                           'num'    => [
                                               'exp',
                                               'num+1'
                                           ],
                                           'is_new' => 0
                                       ]);
                    } else {
                        $data = [
                            'user_id'     => $this->user_info['id'],
                            'target_id'   => $award_detail['target_id'],
                            'is_new'      => 1,
                            'target_type' => $award_detail['target_type'],
                            'num'         => $award_detail['num'],
                            'create_time' => time()
                        ];
                        $table->insert($data);
                    }
                    Db::name('reward_log')
                      ->insert([
                                   'user_id'     => $this->user_info['id'],
                                   'user_name'   => $this->user_info['display_name'],
                                   'remark'      => '领取登录奖励',
                                   'stage'       => 'login',
                                   'extra_int'   => $award_detail['id'],
                                   'create_time' => time(),
                                   'target_id'   => $award_detail['target_id'],
                                   'target_type' => $award_detail['target_type']
                               ]);
                    Db::commit();
                    //更新用户formid 2018-04-19 18:07:42
                    $formid_expires_time = time() + 6 * 24 * 3600;//表单id过期时间
                    $res                 = db('user')
                        ->where(['id' => $this->user_info['id']])
                        ->update([
                                     'formid'              => input('formid'),
                                     'formid_expires_time' => $formid_expires_time
                                 ]);//
                    return $this->json_success('ok', '领取成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    return $this->json_error('宝箱领取失败'.$e->getMessage());
                }

            }
        }

        return $this->json_error('已领取奖励');

    }


    /**
     * 用户物品列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userGoodsList()
    {
        $list_box  = Db::name('user_goods')
                       ->alias('s')
                       ->field('s.id,s.num,name,logo,remark,target_type')
                       ->join('zp_box b', 's.target_id=b.id')
                       ->where([
                                   'target_type' => 1,
                                   'user_id'     => $this->user_info['id'],
                                   's.num'       => [
                                       '>',
                                       0
                                   ]
                               ])
                       ->select();
        $list_prop = Db::name('user_goods')
                       ->alias('s')
                       ->field('s.id,s.num,name,logo,remark,target_type')
                       ->join('zp_prop p', 's.target_id=p.id')
                       ->where([
                                   'type'        => [
                                       '<',
                                       4
                                   ],
                                   'target_type' => 2,
                                   'user_id'     => $this->user_info['id'],
                                   's.num'       => [
                                       '>',
                                       0
                                   ]
                               ])
                       ->select();
        /** @var array $list_box */
        $lists = array_merge($list_box, $list_prop);
        if ($lists) {
            foreach ($lists as &$item) {
                $item['remark'] = explode('|', $item['remark']);
            }
            return $this->json_success('ok', $lists);
        }
        return $this->json_error('暂无数据');
    }


    /**
     * 领取物品
     *
     * @param $target_id int  物品id
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     * @return string
     */
    public function updateUserGoods($target_id = 0)
    {
        $table = Db::name('user_goods');
        $goods = $table->where([
                                   'user_id'   => $this->user_info['id'],
                                   'target_id' => $target_id
                               ])
                       ->find();
        if ($goods && $target_id) {
            $res = $table->where('id', $goods['id'])
                         ->update([
                                      'num'    => [
                                          'exp',
                                          'num+1'
                                      ],
                                      'is_new' => 0
                                  ]);
        } else {
            $systemGoodsList = Db::name('system_reward')
                                 ->where('target_id', $target_id)
                                 ->find();
            //系统中没有该无物品
            if (!$systemGoodsList) {
                $res = 0;
            } else {
                $data = [
                    'user_id'     => $this->user_info['id'],
                    'target_id'   => $target_id,
                    'is_new'      => 1,
                    'target_type' => $systemGoodsList['target_type'],
                    'num'         => 1,
                    'create_time' => time()
                ];
                $res  = $table->insert($data);
            }

        }
        if ($res) {
            return $this->json_success('ok', '领取成功');
        }
        return $this->json_error('领取失败');

    }


    /**
     * 使用物品
     *
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function useGoods()
    {
        $table      = Db::name('user_goods');
        $id         = input('post.id');
        $type       = (int)input('post.type');
        $user_goods = $table->field('num,target_id')
                            ->where('id', $id)
                            ->find();
        if ($user_goods['num'] <= 0) {
            return $this->json_error('物品数量不足');
        }
        if ($id && $type) {
            if ($type === 1) {
                $detail = Db::name('box')
                            ->where('id', $user_goods['target_id'])
                            ->find();
            } else if ($type === 2) {
                $detail = Db::name('prop')
                            ->where('id', $user_goods['target_id'])
                            ->find();
            } else {
                return $this->json_error('道具使用失败');
            }
            if ($detail) {
                if ($type === 1) {
                    $box_table = Db::name('box');

                    $box_info = $box_table->field('reward_prop_type')
                                          ->where('status', 1)
                                          ->find();
                    $temps    = [];
                    $list     = Db::name('prop')
                                  ->whereIn('type', $box_info['reward_prop_type'])
                                  ->select();

                    if ((int)$detail['num'] === 0) {
                        return $this->json_error('数据错误');
                    }
                    for ($i = 0; $i < $detail['num']; $i++) {
                        /** @var array $list */
                        $temps[] = $list[array_rand($list, 1)];
                    }

                    Db::startTrans();

                    try {
                        foreach ($temps as $item) {
                            $goods = $table->where([
                                                       'user_id'     => $this->user_info['id'],
                                                       'target_id'   => $item['id'],
                                                       'target_type' => 2
                                                   ])
                                           ->find();
                            if ($goods) {
                                $table->where('id', $goods['id'])
                                      ->update([
                                                   'num'    => [
                                                       'exp',
                                                       'num+1'
                                                   ],
                                                   'is_new' => 0
                                               ]);
                            } else {
                                $data = [
                                    'user_id'     => $this->user_info['id'],
                                    'target_id'   => $item['id'],
                                    'is_new'      => 1,
                                    'target_type' => 2,
                                    'num'         => 1,
                                    'create_time' => time()
                                ];
                                $table->insert($data);
                            }
                        }
                        $open_temps = [];
                        foreach ($temps as $v) {
                            if (isset($open_temps[$v['id']])) {
                                $open_temps[$v['id']]['open_num'] += 1;
                            } else {
                                $open_temps[$v['id']]             = $v;
                                $open_temps[$v['id']]['open_num'] = 1;
                            }
                        }
                        $remarks = [];
                        foreach ($open_temps as $o) {
                            $remarks[] = $o['name'].'x'.$o['open_num'];
                        }
                        $remark = join(',', $remarks);
                        Db::name('reward_log')
                          ->insert([
                                       'user_id'     => $this->user_info['id'],
                                       'user_name'   => $this->user_info['display_name'],
                                       'remark'      => '使用了'.$detail['name'],
                                       'stage'       => 'use_box',
                                       'create_time' => time(),
                                       'target_id'   => $user_goods['target_id'],
                                       'target_type' => 1
                                   ]);
                        Db::name('reward_log')
                          ->insert([
                                       'user_id'     => $this->user_info['id'],
                                       'user_name'   => $this->user_info['display_name'],
                                       'remark'      => '获得了'.$remark,
                                       'stage'       => 'get_prop',
                                       'create_time' => time(),
                                       'target_id'   => $user_goods['target_id'],
                                       'target_type' => 1
                                   ]);
                        $table->where('id', $id)
                              ->setDec('num');


                        Db::commit();
                        $box_open_detail = [
                            'logo' => $detail['logo'],
                            'name' => $detail['name'],
                            'list' => $open_temps
                        ];
                        return $this->json_success('ok', $box_open_detail);

                    } catch (\Exception $e) {
                        Db::rollback();
                        return $this->json_error('宝箱领取失败'.$e->getMessage());
                    }
                } else if ($type === 2) {
                    $info_extend_table = Db::name('user_info_extend');
                    $info              = $info_extend_table->where('user_id', $this->user_info['id'])
                                                           ->find();

                    Db::startTrans();
                    try {
                        if (!$detail['action_type'] && $detail['type'] == 3) {
                            Db::name('user')
                              ->where('id', $this->user_info['id'])
                              ->setInc('points', $detail['reward_val']);
                        } else {
                            $extend_arr = [
                                1 => [
                                    1 => 'exp_limit_num',
                                    2 => 'exp_limit_time'
                                ],
                                2 => [1 => 'jf_limit_num'],
                                3 => [
                                    1 => 'point_limit_num',
                                    2 => 'point_limit_time'
                                ]
                            ];
                            $field      = $extend_arr[$detail['type']][$detail['action_type']];
                            //加时间
                            if ((int)$detail['action_type'] === 2) {
                                if (!$info[$field] || $info[$field] < time()) {
                                    $info[$field] = time();
                                }
                                $value = strtotime($detail['reward_val'].' hours ', $info[$field]);
                            } else {
                                $value = $info[$field] + $detail['reward_val'];
                            }
                            if ($info) {
                                $data = [
                                    $field => $value
                                ];
                                $info_extend_table->where('user_id', $this->user_info['id'])
                                                  ->update($data);

                            } else {
                                $data         = [
                                    'user_id' => $this->user_info['id'],
                                    $field    => $value
                                ];
                                $data[$field] = $info_extend_table->insert($data);
                            }
                        }
                        Db::name('reward_log')
                          ->insert([
                                       'user_id'     => $this->user_info['id'],
                                       'user_name'   => $this->user_info['display_name'],
                                       'remark'      => '使用道具',
                                       'stage'       => 'use_prop',
                                       'create_time' => time(),
                                       'target_id'   => $user_goods['target_id'],
                                       'target_type' => 1
                                   ]);
                        $table->where('id', $id)
                              ->update([
                                           'num' => [
                                               'exp',
                                               'num-1'
                                           ]
                                       ]);
                        Db::commit();
                        return $this->json_success('ok', '领取成功');
                    } catch (\Exception $e) {
                        Db::rollback();
                    }
                }
            } else {
                return $this->json_error('没有该物品');
            }
        }
        return $this->json_error('道具使用失败');
    }

    /**
     * 商店
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsList()
    {
        $list       = db('goods')
            ->where('status', 1)
            ->order('sort desc')
            ->select();
        $data       = [];
        $best_goods = [];
        $goods      = [];
        foreach ($list as $value) {
            if ($value['is_best'] == 1) {
                $best_goods[] = $value;
            } else {
                $goods[] = $value;
            }
            $data['shop'] = [
                'best_goods' => $best_goods,
                'goods'      => $goods
            ];
        }

        if ($list) {
            $data['share_points'] = config('share_shop')['points'];//分享金币数
            return $this->json_success('ok', $data);
        } else {
            return $this->json_error('暂无数据');
        }
    }

}